import { fileManager } from "../utils/fileUtils"
import toastManager from "../utils/toastManager"
import Search1n from "../VecDbModel/search"
import Logger from '../utils/Logger'
import { DBtasksteps } from "../utils/recallInterface"

export default class LLMtaskManager {
  p1 = new toastManager()
  f1 = null
  task = ""
  extraInfo = ""
  taskStatus = "NotCompleted"
  pageDescH = ""
  prompt = ""
  lastPrompt = ""
  sameCnt = 0
  historyTaskStatus = []
  AlreadyCompleted =
    "=>Based on your previous replies and common sense about modern phone system, If the task is already fulfilled without further action, fill in \"AlreadyCompleted\".\n"
  NotCompleted =
    "=>If the task needs further action to be fulfilled, fill in \"NotCompleted\".\n"
  NoClue =
    "=>After you have scrutinized this task and thought of the implied tasks intailed by this task, If you believe even traversing further from this page will still not lead to the completion of this task, fill in \"NoClue\".And fill targetId with-1).\n"

  constructor(dir = "") {
    console.error("_:LLMtaskManager constructed")
    this.f1 = new fileManager(dir)
    if (dir != "") {
      this.task = this.f1.gettask()
        .replace("执行任务", "")
        .replace("execute task", "")
        .replace("学习任务", "")
        .replace("learn task", "")
    }
  }

  getStatusPrompt() {
    if (this.historyTaskStatus.length == 1 && this.historyTaskStatus[0] == "NotCompleted") {
      return this.AlreadyCompleted + this.NotCompleted
    }
    return this.AlreadyCompleted + this.NotCompleted + this.NoClue
  }

  settaskStatus(taskStatus) {
    this.historyTaskStatus.push(taskStatus)
    this.taskStatus = taskStatus
  }

  print() {
    let TAG = "_:_[Task]"
    let TAG2 = "_:_[    ]"
    console.log(TAG, "taskStatus", this.taskStatus, "task", this.task)
    console.log(TAG2, "extraInfo", this.extraInfo)
    console.log(TAG2, "pageDescH", this.pageDescH)
    console.log(TAG2, "sameCnt", this.sameCnt)
  }

  async getPrompt(pageDescH) {
    let TAG = "_:_[task_prompt]"
    let sumStr = ""
    console.log(TAG, "entered")
    try {
      console.log(TAG, "historyStatusLenght", this.historyTaskStatus.length, this.historyTaskStatus)
      if (this.historyTaskStatus.length == 1 && this.historyTaskStatus[0] == "NotCompleted") {
        let simList = await Search1n<DBtasksteps>(this.task, "tasksteps", 2)
        let historyStr = ""
        for (let i = 0; i < simList.length; i++) {
          historyStr += "=>[" + i + "] task:<" + simList[i].origin.name + "> with steps <" + simList[i].origin.steps +
            ">"
        }
        if (simList.length > 0) {
          sumStr =
            "{{你可以参考的历史任务和当时的操作：" + historyStr + "}}"
        }
        console.log(TAG, "simListLengh", simList.length, "learned history", sumStr)
      }
      let taskStatusPrompt = this.getStatusPrompt()
      this.pageDescH = pageDescH
      this.prompt =
        " 你的任务是： " + this.task + sumStr + "。现在有个手机页面GUI的JSON：" + this.pageDescH + this.extraInfo +
          "。请选择一个CLICKABLE或SCROLLABLE组件的id，以如下格式返回结果：" +
          "{taskStatus:string(based on the page descriptions and the task:" +
          taskStatusPrompt +
          "pageDesc:string(use Chinese.please describe the main functionalities of this GUI.please limit its length to 10 words)," +
          "action:string(click;scrollForward(to increase the value of a certain element or scroll the page further forward);scrollBackward)," +
          "targetText:string(If the target element of the json has text,fill in here, else, fill in \"\""
          "targetId:number(if you have keyCode to press, fill in -1 here.Note that ONLY CLICKABLE OR SCROLLABLE OR TEXTINPUT ELEMENT CAN BE THE TARGET)," +
          "text:string(if the component you selected is a TextArea or TextInput, fill in text THAT YOU WANT TO INPUT here, else, fill in N/A}," +
          "keyCode:number(Here defines some keyCode that you can call if needed.Else, fill in -1." +
          "VOLUME_UP=16 VOLUMN_DOWN=17 SHOOT_CAMERA=19)," +
          // "willTurn:bool(if you can be 90 percent sure that operation on the target element can not lead to page to turn, fill in false.If you are not sure, fill in true)" +
          "你的回答只能只能输出字符串的标准JSON格式，不能有其他格式回答"
      if (this.lastPrompt == this.prompt) {
        this.sameCnt++
      } else {
        this.sameCnt = 0
      }
      this.lastPrompt = this.prompt
      console.log(TAG, "sending to llm:", this.prompt.replace(/\n/g, ""))
      return this.prompt
    } catch (e) {
      console.log(TAG, e)
    }
  }
}